//
//  UINavigationBar+Flat.swift
//  Segmentio
//
//  Created by yiwanjun Demchenko
//  Copyright © 2016 Yalantis Mobile. All rights reserved.
//

import UIKit

private var flatAssociatedObjectKey: UInt8 = 0


@objc @IBDesignable public extension UINavigationBar {
    
    /*
     An extension that adds a "flat" field to UINavigationBar. This flag, when
     enabled, removes the shadow under the navigation bar.
     */
    @IBInspectable var flat: Bool {
        get {
            guard let obj = objc_getAssociatedObject(self, &flatAssociatedObjectKey) as? NSNumber else {
                return false
            }
            return obj.boolValue;
        }
        
        set {
            if (newValue) {
                let void = UIImage()
                setBackgroundImage(void, for: .any, barMetrics: .default)
                shadowImage = void
            } else {
                setBackgroundImage(nil, for: .any, barMetrics: .default)
                shadowImage = nil
            }
            objc_setAssociatedObject(self, &flatAssociatedObjectKey, NSNumber(value: newValue as Bool),
                                     objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    /// 设置背景色
    /// - Parameters:
    ///   - color: 颜色
    ///   - lineColor: 底部线的颜色
    ///   - showShadowLine: 是否显示阴影线
    ///   UINavigationBar有个属性 isTranslucent 是否为透明， 为 true 会使 currentViewController 的内容顶部顶到 statusBar
    func setBackgroundColor(color : UIColor, lineColor: UIColor, showShadowLine: Bool = false){
        
        if #available(iOS 13.0, *) {
            let app = UINavigationBarAppearance()
            app.configureWithOpaqueBackground()  // 重置背景和阴影颜色
            if let titleAtt = UINavigationBar.appearance().titleTextAttributes {
                app.titleTextAttributes = titleAtt
            }
            
            app.backgroundColor = color  // 设置导航栏背景色
            if showShadowLine == false {
                app.shadowImage = UIColor.clear.toImage(size: CGSize(width: UIScreen.main.bounds.width, height: 1))//设置导航栏下边界分割线透明
            }else {
                app.shadowImage = lineColor.toImage(size: CGSize(width: UIScreen.main.bounds.width, height: 1))
            }
            scrollEdgeAppearance = app  // 带scroll滑动的页面
            standardAppearance = app // 常规页面
            
        } else {
            setBackgroundImage(UIImage.image(from: color, size:  CGSize(width: 100, height: 100)), for: .default)
            if showShadowLine == false {
                shadowImage = UIImage()
            }else{
                shadowImage = lineColor.toImage(size: CGSize(width: UIScreen.main.bounds.width, height: 1))
            }
        }
    }
}


